<?php
declare(strict_types=1);

namespace App\Controller\WsWorker;

use App\Component\RedisGroupSever;
use App\Component\RedisUserSever;
use App\Component\Server;
use Hyperf\Utils\Codec\Json;


class Join
{

    public static function joinRoom($fd, $data)
    {
        $room = $data["room"];

        $redisUser = new RedisUserSever();
        $token = $data["token"];
        $userId = $redisUser->getUserByToken($token);
        $user = Json::decode($redisUser->getUserInfo($userId));
        $oldFds = $redisUser->getUserAllFD($userId);
        foreach ($oldFds as $oldFd){
            Close::close($oldFd);
        }

        $redisUser->setUserFD($fd, $user["id"]);
        $redisUser->setUserByFd($fd, $user["id"]);

        $redisGroup = new RedisGroupSever();
        $redisGroup->joinRoom($room, $fd);
        $roomData = $redisGroup->getRoom($room);


        $msg = [
            "type"        => $data["type"],
            "room"        => $room,
            "num"         => count($roomData),
            "client_name" => $user["name"],
            "client_img"  => $user["img"],
            "content"     => "进入了聊天室"
        ];

        Server::sendToAll(Json::encode($msg), $roomData);
    }
}